package screen;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.Vector;

import javax.microedition.content.ContentHandler;
import javax.microedition.content.ContentHandlerException;
import javax.microedition.content.Invocation;
import javax.microedition.content.Registry;

import localization.alarmclockResource;
import net.rim.blackberry.api.browser.Browser;
import net.rim.blackberry.api.browser.BrowserSession;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.i18n.SimpleDateFormat;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.system.RealtimeClockListener;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.FontManager;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.TouchGesture;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.pane.HorizontalScrollableController;
import net.rim.device.api.ui.component.pane.HorizontalScrollableTitleView;
import net.rim.device.api.ui.component.pane.Pane;
import net.rim.device.api.ui.component.pane.PaneManagerModel;
import net.rim.device.api.ui.component.pane.PaneManagerView;
import net.rim.device.api.ui.component.pane.PaneView;
import net.rim.device.api.ui.component.pane.TitleView;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.menu.SubMenu;
import net.rim.device.api.util.DateTimeUtilities;
import net.rim.device.api.util.MathUtilities;
import net.rim.device.api.util.StringProvider;
import code.AlarmClockSettings;
import code.AppSettings;
import code.BirthdayReminderSettings;
import code.Config;
import code.Function;
import code.LunarCalendar;
import code.WorldClockSettings;
import ctrl.ForegroundManager;
import ctrl.ListStyleButtonField;
import ctrl.ListStyleButtonSet;

public final class AlarmClockScreen extends MainScreen implements RealtimeClockListener, alarmclockResource
{
	private static PersistentObject _store;
	private static Vector _data;
	private static Vector _dataAlarmClockSettings;
	private static Vector _dataWorldClockSettings;
	private static Vector _dataBirthdayReminderSettings;
	private static Vector _dataAppSettings;
	
	private PaneManagerView _paneManagerView;
	
	private ListStyleButtonSet _worldClockSet=new ListStyleButtonSet();
	private ListStyleButtonSet _alarmClockSet=new ListStyleButtonSet();
	private ListStyleButtonSet _birthdayReminderSet=new ListStyleButtonSet();
	
	private String[] labelTitles=getResStringArray(LABEL_TITLES);
	private String[] TIMEZONE_DIGITS;
	private static ResourceBundle _resources = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);
	
    public AlarmClockScreen()
    {
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT);
		
    	HorizontalFieldManager appTitlehManager=new HorizontalFieldManager(USE_ALL_WIDTH);
    	
    	BitmapField appTitleBitmap=new BitmapField(Bitmap.getBitmapResource(Config.titleIconName));
    	appTitleBitmap.setSpace(5, 5);
    	LabelField appTitleLabel=new LabelField(Config.APP_TITLE, FIELD_VCENTER);
    	//appTitleLabel.setFont(Config.FONT_APP_TITLE);

    	appTitlehManager.add(appTitleBitmap);
    	appTitlehManager.add(appTitleLabel);
    	appTitlehManager.setBackground(Config.bgColor_Gradient);
    	setTitle(appTitlehManager);
        
    	Font _appFont;
    	try {
			FontFamily family=FontFamily.forName("BBGlobal Sans");
			_appFont=family.getFont(Font.PLAIN, 8, Ui.UNITS_pt);
			FontManager.getInstance().setApplicationFont(_appFont);
		} catch (ClassNotFoundException e) {e.printStackTrace();}

		TIMEZONE_DIGITS=Function.getTimezoneDigits();
    	
        createUiPaneView();

        refreshWorldClockSet();
        refreshBirthdayReminderSet();
        
    	_alarmClockSet.setFocus();
        
        Application.getApplication().addRealtimeClockListener(this);
    }
        
    private void createUiPaneView()
    {	
    	LabelField labelTitle0=new LabelField(labelTitles[0]) {protected void paint(Graphics g) {g.setColor(Color.WHITE); super.paint(g);}};
    	LabelField labelTitle1=new LabelField(labelTitles[1]) {protected void paint(Graphics g) {g.setColor(Color.WHITE); super.paint(g);}};
    	LabelField labelTitle2=new LabelField(labelTitles[2]) {protected void paint(Graphics g) {g.setColor(Color.WHITE); super.paint(g);}};
    	labelTitle0.setFont(Config.FONT_PANEVIEW_TITLE);
    	labelTitle1.setFont(Config.FONT_PANEVIEW_TITLE);
    	labelTitle2.setFont(Config.FONT_PANEVIEW_TITLE);
    	
    	Pane pane0=new Pane(labelTitle0, createUiAlarmClock());
    	Pane pane1=new Pane(labelTitle1, createUiWorldClock());
    	Pane pane2=new Pane(labelTitle2, createUiReminder());
    	
    	PaneManagerModel model=new PaneManagerModel();
    	model.addPane(pane0); model.addPane(pane1); model.addPane(pane2);
    	model.setCurrentlySelectedIndex(0);
    	model.enableLooping(true);
    	
    	TitleView titleView=new HorizontalScrollableTitleView(FOCUSABLE);
    	titleView.setModel(model);

    	PaneView paneView=new PaneView(Field.FOCUSABLE);
    	paneView.setModel(model);
    	
    	_paneManagerView=new PaneManagerView(Field.FOCUSABLE, titleView, paneView) {
    		protected boolean touchEvent(TouchEvent event)
    		{
    			if(event.getEvent()==TouchEvent.GESTURE)
    			{
    				TouchGesture gesture=event.getGesture();
    				if(gesture.getEvent()==TouchGesture.SWIPE)
    				{
    					//if(_paneManagerView.isAnimating()) {return true;}
    					
    					switch(gesture.getSwipeDirection())
    					{
    						case TouchGesture.SWIPE_EAST:
    						case TouchGesture.SWIPE_WEST:
    							UiApplication.getUiApplication().invokeLater(new Runnable()
    							{
									public void run() {
		    							switch(_paneManagerView.getModel().currentlySelectedIndex())
		    							{
											case 0:
												_alarmClockSet.setFocus();									
												break;
											case 1:
												_worldClockSet.setFocus();
												break;
											case 2:
												_birthdayReminderSet.setFocus();
												break;
										}
									}
								});
    					}
    				}
    			}
    			
    			return super.touchEvent(event);
    		};
    	};
    	_paneManagerView.setModel(model);
    	model.setView(_paneManagerView);

    	HorizontalScrollableController controller=new HorizontalScrollableController();
    	controller.setModel(model);
    	controller.setView(_paneManagerView);
    	model.setController(controller);
    	_paneManagerView.setController(controller);

    	add(_paneManagerView);
    }
    
    private void doAnimatingPanes(final int currentPane, final int direction)
    {
		UiApplication.getUiApplication().invokeAndWait(new Runnable()
		{
			public void run() {
				_paneManagerView.jumpTo(currentPane, direction);
				_paneManagerView.getModel().setCurrentlySelectedIndex(currentPane, false);
			}
		});    	
    }
    
    private ForegroundManager createUiAlarmClock()
    {
    	ForegroundManager _foreground=new ForegroundManager(0) {
    		protected boolean navigationMovement(int dx, int dy, int status, int time)
    	    {
    			_alarmClockSet.getFocus();
    			
    			if(_paneManagerView.isAnimating()) {return true;}
    			
    			if(dx<0)
    			{
    				doAnimatingPanes(2, PaneManagerView.DIRECTION_BACKWARDS);
					_birthdayReminderSet.setFocus();
					
    				return true;
    			} 
    			
    			if(dx>0)
    			{
    				doAnimatingPanes(1, PaneManagerView.DIRECTION_FORWARDS);
					_worldClockSet.setFocus();
					
    				return true;
    			}
    			
    			return super.navigationMovement(dx, dy, status, time);
    	    }
    	};
        
    	ListStyleButtonField link=new ListStyleButtonField("Alarm at 06:30", "6:30","Weekdays", true); 
    	_alarmClockSet.add(link);

    	link=new ListStyleButtonField("Alarm at Holiday", "10:30","Weekends", false); 
    	_alarmClockSet.add(link);

    	link=new ListStyleButtonField("Alarm at", "18:49","Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun", false); 
    	_alarmClockSet.add(link);
    	
        _foreground.add(_alarmClockSet);
        
        return _foreground;
    }
    
    private ForegroundManager createUiReminder()
    {
    	ForegroundManager _foreground=new ForegroundManager(0) {
    		protected boolean navigationMovement(int dx, int dy, int status, int time)
    	    {
    			_birthdayReminderSet.getFocus();
    			
    			if(_paneManagerView.isAnimating()) {return true;}
    			
    			if(dx<0)
    			{
    				doAnimatingPanes(1, PaneManagerView.DIRECTION_BACKWARDS);
					_worldClockSet.setFocus();
					
					return true;
    			} 
    			
    			if(dx>0)
    			{
    				doAnimatingPanes(0, PaneManagerView.DIRECTION_FORWARDS);
					_alarmClockSet.setFocus();
					
    				return true;
    			}
    			
    			return super.navigationMovement(dx, dy, status, time);
    	    }
    	};
    	
    	_foreground.add(_birthdayReminderSet);
    	
    	return _foreground;
    }

    private ForegroundManager createUiWorldClock()
    {
    	ForegroundManager _foreground=new ForegroundManager(0) {
    		protected boolean navigationMovement(int dx, int dy, int status, int time)
    	    {
    			_worldClockSet.getFocus();
    			
				if(_paneManagerView.isAnimating()) {return true;}
				
    			if(dx<0)
    			{
    				doAnimatingPanes(0, PaneManagerView.DIRECTION_BACKWARDS);
			    	_alarmClockSet.setFocus();
			    	
    				return true;
    			} 
    			
    			if(dx>0)
    			{
    				doAnimatingPanes(2, PaneManagerView.DIRECTION_FORWARDS);
					_birthdayReminderSet.setFocus();
					
	   				return true;
    			}
    			
    			return super.navigationMovement(dx, dy, status, time);
    	    }
    	};

		_foreground.add(_worldClockSet);
    	
    	return _foreground;
    }

    private void refreshWorldClockSet()
    {
		ListStyleButtonField link;
		
		refreshStore();
		_worldClockSet.setFocus();
		_worldClockSet.deleteAll();

		if(_dataWorldClockSettings.size()>0)
		{
			for(int i=0; i<_dataWorldClockSettings.size(); i++)
			{
				final WorldClockSettings settings=(WorldClockSettings) _dataWorldClockSettings.elementAt(i);
				final int index=i;
				link=new ListStyleButtonField("", "", "")
				{
					protected void fieldChangeNotify(int context)
					{
			    		NewWorldClockScreen worldClockScreen=new NewWorldClockScreen(settings, index);
			    		UiApplication.getUiApplication().pushModalScreen(worldClockScreen);
			    		
			    		if(worldClockScreen.isModified()) {refreshWorldClockSet();}
			    		
			    		worldClockScreen=null;
					}
				};
				_worldClockSet.add(link);
			}
			clockUpdated();
		} else {
			_worldClockSet.add(new LabelField(getResString(LABEL_TIPS_MANAGER_EMPTY), FOCUSABLE | USE_ALL_WIDTH));
		}
		
		setFocusOnPaneView();
    }

    private void refreshBirthdayReminderSet()
    {
		ListStyleButtonField link;
		
		refreshStore();
		_birthdayReminderSet.setFocus();
		_birthdayReminderSet.deleteAll();

		if(_dataBirthdayReminderSettings.size()>0)
		{
			for(int i=0; i<_dataBirthdayReminderSettings.size(); i++)
			{
				final BirthdayReminderSettings settings=(BirthdayReminderSettings) _dataBirthdayReminderSettings.elementAt(i);
				final int index=i;
				link=new ListStyleButtonField("", "", getResString(TIPS_REMAINING), "")
				{
					protected void fieldChangeNotify(int context)
					{
			    		NewBirthdayReminderScreen birthdayReminderScreen=new NewBirthdayReminderScreen(settings, index);
			    		UiApplication.getUiApplication().pushModalScreen(birthdayReminderScreen);
			    		
			    		if(birthdayReminderScreen.isModified()) {refreshBirthdayReminderSet();}
			    		
			    		birthdayReminderScreen=null;
					}
				};
				_birthdayReminderSet.add(link);
			}
			clockUpdated();
		} else {
			_birthdayReminderSet.add(new LabelField(getResString(LABEL_TIPS_MANAGER_EMPTY), FOCUSABLE | USE_ALL_WIDTH));
		}
		
		setFocusOnPaneView();
    }

    static
	{
    	_store=PersistentStore.getPersistentObject(0xaa041103a4a17b66L); //blackberry_alarmclock_worldclock_settings_id
		refreshStore();
	}

    private void setFocusOnPaneView()
    {
    	if(_paneManagerView!=null)
		{
			switch (_paneManagerView.getModel().currentlySelectedIndex())
			{
				case 0:
					_alarmClockSet.setFocus();
					break;
				case 1:
					_worldClockSet.setFocus();
					break;
				case 2:
					_birthdayReminderSet.setFocus();
					break;
			}
		}	
    }
    
    private static void saveData()
    {
		_data.removeAllElements();
		
		if(!_dataAppSettings.isEmpty()) {for(int i=0; i<_dataAppSettings.size(); i++) {_data.addElement(_dataAppSettings.elementAt(i));}}
		if(!_dataAlarmClockSettings.isEmpty()) {for(int i=0; i<_dataAlarmClockSettings.size(); i++) {_data.addElement(_dataAlarmClockSettings.elementAt(i));}}
		if(!_dataWorldClockSettings.isEmpty()) {for(int i=0; i<_dataWorldClockSettings.size(); i++) {_data.addElement(_dataWorldClockSettings.elementAt(i));}}
		if(!_dataBirthdayReminderSettings.isEmpty()) {for(int i=0; i<_dataBirthdayReminderSettings.size(); i++) {_data.addElement(_dataBirthdayReminderSettings.elementAt(i));}}
		
		if(!_data.isEmpty())
		{
			synchronized(_store)
			{
				_store.setContents(_data);
				_store.commit();
			}
		}
    }
    
    private static void refreshStore()
    {
		synchronized(_store)
		{
			if(_store.getContents()==null)
			{
				_store.setContents(new Vector());
				_store.forceCommit();
			}
		}
		
		try {
			_dataAlarmClockSettings=new Vector();
			_dataWorldClockSettings=new Vector();
			_dataBirthdayReminderSettings=new Vector();
			_dataAppSettings=new Vector();
			
			_data=new Vector();
			_data=(Vector) _store.getContents();
			
	    	for(int i=0; i<_data.size(); i++)
	    	{
	    		if(_data.elementAt(i) instanceof AlarmClockSettings) {_dataAlarmClockSettings.addElement(_data.elementAt(i));}
	    		else if(_data.elementAt(i) instanceof WorldClockSettings) {_dataWorldClockSettings.addElement(_data.elementAt(i));}
	    		else if(_data.elementAt(i) instanceof BirthdayReminderSettings) {_dataBirthdayReminderSettings.addElement(_data.elementAt(i));}
	    		else if(_data.elementAt(i) instanceof AppSettings) {_dataAppSettings.addElement(_data.elementAt(i));}
	    	}
		} catch (final Exception e) {}
    }
    
    private void deleteItem()
    {
    	Field field;
		int index=_paneManagerView.getModel().currentlySelectedIndex();
		
		switch (index) {
		case 0:
			field=_alarmClockSet.getLeafFieldWithFocus();
			
			if(field instanceof ListStyleButtonField)
			{
				//
			}
			
			break;
		case 1:
			field=_worldClockSet.getLeafFieldWithFocus();
			
			if(field instanceof ListStyleButtonField)
			{
				_dataWorldClockSettings.removeElementAt(field.getIndex());
				
				saveData();
				refreshWorldClockSet();
			}
			
			break;
		case 2:
			field=_birthdayReminderSet.getLeafFieldWithFocus();
			
			if(field instanceof ListStyleButtonField)
			{
				_dataBirthdayReminderSettings.removeElementAt(field.getIndex());
				
				saveData();
				refreshBirthdayReminderSet();
			}

			break;
		}
    }
    
  	private String getLunar(int year, int month, int day)
  	{
  	    long[] l = LunarCalendar.Lunar(year, month, day);
  	    
	    String month1 = (int) l[3]==1 ? "闰 " : "";
	    switch((int) l[1])
	    {
	      	case 1:month1+="一月";break;
	      	case 2:month1+="二月";break;
	      	case 3:month1+="三月";break;
	      	case 4:month1+="四月";break;
	      	case 5:month1+="五月";break;
	      	case 6:month1+="六月";break;
	      	case 7:month1+="七月";break;
	      	case 8:month1+="八月";break;
	      	case 9:month1+="九月";break;
	      	case 10:month1+="十月";break;
	      	case 11:month1+="冬月";break;
	      	case 12:month1+="腊月";break;
	    }
  	    
  	    return " (" + month1 + LunarCalendar.cDay((int)(l[2])) + ")";
  	}

	
    
//*************************************************************//
//**********************    Fucntions    **********************//
//*************************************************************//
    private String getResString(int key)
	{
		return _resources.getString(key);
	}

    private String[] getResStringArray(int key)
	{
    	return _resources.getStringArray(key);
	}

    private void openAppWorld(String myContentId) throws IllegalArgumentException, ContentHandlerException, SecurityException, IOException 
    {
        Registry registry = Registry.getRegistry(AlarmClockScreen.class.getName());
        Invocation invocation = new Invocation( null, null, "net.rim.bb.appworld.Content", true, ContentHandler.ACTION_OPEN );

        invocation.setArgs(new String[] {myContentId});

        boolean mustExit = registry.invoke(invocation);
        if(mustExit) {UiApplication.getUiApplication().popScreen(this);}
    }


	
    //**************************************************************//
    //**********************  Menu Functions  **********************//
    //**********************        &&        **********************//
    //**********************  Menu Overrides  **********************//
    //**************************************************************//
	private MenuItem menuCleanData=new MenuItem(new StringProvider("Clean Data"), 200, 10)
	{
		public void run()
		{
			synchronized(_store)
			{
				_store.setContents(new Vector());
				_store.forceCommit();
			}
		}
	};
	
    private MenuItem menuSettings=new MenuItem(new StringProvider(getResString(MENU_SETTINGS)), 80, 10)
    {
    	public void run()
    	{
    		SettingsScreen settingsScreen=new SettingsScreen();
    		UiApplication.getUiApplication().pushModalScreen(settingsScreen);
    		
    		if(settingsScreen.isModified())
    		{
    			int fontSize=settingsScreen.getFontSize();
    			
    			_alarmClockSet.setChildFontSize(fontSize);
    			_worldClockSet.setChildFontSize(fontSize);
    			_birthdayReminderSet.setChildFontSize(fontSize);
    		}
    		
    		settingsScreen=null;
    	}
    };

    private MenuItem menuAbout=new MenuItem(new StringProvider(getResString(MENU_ABOUT_HELP)), 90, 10)
    {
    	public void run()
    	{
    		UiApplication.getUiApplication().pushScreen(new AboutScreen());
    	}
    };

    private MenuItem menuCloseApp=new MenuItem(new StringProvider(getResString(MENU_APP_CLOSE)), 100, 10)
    {
    	public void run(){
        	onClose();
    	}
    };

    private MenuItem menuForceExit=new MenuItem(new StringProvider(getResString(MENU_APP_FORCE_EXIT)), 110, 10)
    {
    	public void run(){
        	System.exit(0);
    	}
    };

    private MenuItem menuWriteAReview=new MenuItem(new StringProvider(getResString(MENU_BBWORLD_WRITE_A_REVIEW)), 10, 10)
    {
    	public void run()
    	{
    		try
            {
                openAppWorld("25682903");
            } catch(final Exception e)
            {
                UiApplication.getUiApplication().invokeLater(new Runnable()
                {
                    public void run()
                    {
                    	if(e instanceof ContentHandlerException)
                    	{
                    		Dialog.alert("BlackBerry World is not installed!");
                    	} else {
                    		Dialog.alert( "Problems opening App World: " + e.getMessage() );
                    	}
                    }
                });
            }
    	}
    };

    private MenuItem menuBrowseOtherApps=new MenuItem(new StringProvider(getResString(MENU_BBWORLD_BROWSE_OTHER_APPS)), 20, 10)
    {
    	public void run()
    	{
    		BrowserSession browser=Browser.getDefaultSession();
    		browser.displayPage(Config.BLACKBERRY_WORLD_VENDOR_HOMEPAGE);
    	}
    };

    private MenuItem menuNewAlarmClock=new MenuItem(new StringProvider(labelTitles[0]), 10, 10)
    {
    	public void run()
    	{
    		UiApplication.getUiApplication().pushScreen(new NewAlarmClockScreen());
    	}
    };
    
    private MenuItem menuNewWorldClock=new MenuItem(new StringProvider(labelTitles[1]), 20, 10)
    {
    	public void run()
    	{
    		NewWorldClockScreen worldClockScreen=new NewWorldClockScreen();
    		UiApplication.getUiApplication().pushModalScreen(worldClockScreen);
    		
    		if(worldClockScreen.isModified()) {refreshWorldClockSet();}
    		
    		worldClockScreen=null;
    	}
    };

    private MenuItem menuNewBirthdayReminder=new MenuItem(new StringProvider(labelTitles[2]), 30, 10)
    {
    	public void run()
    	{
    		NewBirthdayReminderScreen birthdayReminderScreen=new NewBirthdayReminderScreen();
    		UiApplication.getUiApplication().pushModalScreen(birthdayReminderScreen);
    		
    		if(birthdayReminderScreen.isModified()) {refreshBirthdayReminderSet();}
    		
    		birthdayReminderScreen=null;
    	}
    };

    private MenuItem menuDeleteItem=new MenuItem(new StringProvider(getResString(MENU_DELETE_ITEM)), 30, 10)
    {
    	public void run()
    	{
    		deleteItem();
    	}
    };
    
    protected void makeMenu(Menu menu,int instance)
    {
    	SubMenu menuBBWorld=new SubMenu(null, "BlackBerry World", 10, 10);
    	menuBBWorld.add(menuWriteAReview);
    	menuBBWorld.addSeparator();
    	menuBBWorld.add(menuBrowseOtherApps);
    	
    	SubMenu menuNewItems=new SubMenu(null, getResString(MENU_ADD_NEW_ITEM), 20, 10);
    	menuNewItems.add(menuNewAlarmClock);
    	menuNewItems.add(menuNewWorldClock);
    	menuNewItems.add(menuNewBirthdayReminder);
    	
    	menu.add(menuBBWorld);
    	menu.addSeparator();
    	menu.add(menuNewItems);
    	menu.addSeparator();
    	menu.add(menuDeleteItem);
    	menu.addSeparator();
    	menu.add(menuSettings);
    	menu.addSeparator();
    	menu.add(menuAbout);
    	menu.addSeparator();
    	menu.add(menuCloseApp);
    	menu.add(menuForceExit);
    	menu.addSeparator();
    	menu.add(menuCleanData);
    	menu.addSeparator();
    }
    
    
    
    //**************************************************************//
    //********************** Override methods **********************//
    //*********************        &&        ***********************//
    //********************** System Listeners **********************//
    //**************************************************************//
	public boolean onClose()
	{
		UiApplication.getApplication().requestBackground();			
    	
    	return true;
	}
	
	protected boolean keyChar(char key, int status, int time)
	{
		if(_paneManagerView.isAnimating()) {return true;}
		
		int currentPane=_paneManagerView.getModel().currentlySelectedIndex();

		if(key==Characters.LATIN_CAPITAL_LETTER_A || key==Characters.LATIN_SMALL_LETTER_A)// && !editNickname.isFocus())
		{
			UiApplication.getUiApplication().pushScreen(new AboutScreen());
			return true;
		} else if(key==Characters.LATIN_CAPITAL_LETTER_W || key==Characters.LATIN_SMALL_LETTER_W || key==Characters.DIGIT_ONE)
		{
			if(currentPane==0) {return true;}
			
			if(currentPane==1)
			{
				doAnimatingPanes(0, PaneManagerView.DIRECTION_BACKWARDS);
			}
			
			if(currentPane==2)
			{
				doAnimatingPanes(0, PaneManagerView.DIRECTION_FORWARDS);
			}

			_alarmClockSet.setFocus();		

			return true;
		} else if(key==Characters.LATIN_CAPITAL_LETTER_E || key==Characters.LATIN_SMALL_LETTER_E || key==Characters.DIGIT_TWO)
		{
			if(currentPane==1) {return true;}
			
			if(currentPane==2)
			{
				doAnimatingPanes(1, PaneManagerView.DIRECTION_BACKWARDS);
			}
			
			if(currentPane==0)
			{
				doAnimatingPanes(1, PaneManagerView.DIRECTION_FORWARDS);
			}
			
			_worldClockSet.setFocus();

			return true;
		} else if(key==Characters.LATIN_CAPITAL_LETTER_D || key==Characters.LATIN_SMALL_LETTER_D || key==Characters.DIGIT_FIVE)
		{
			_paneManagerView.snapToCurrent(PaneManagerView.DIRECTION_BACKWARDS);
			
			return true;
		//} else if(key==Characters.LATIN_CAPITAL_LETTER_F || key==Characters.LATIN_SMALL_LETTER_F || key==Characters.DIGIT_SIX)
		//{
		//	_worldClockSet.invalidate();
		} else if(key==Characters.LATIN_CAPITAL_LETTER_R || key==Characters.LATIN_SMALL_LETTER_R || key==Characters.DIGIT_THREE)
		{
			if(currentPane==2) {return true;}
			
			if(currentPane==0)
			{
				doAnimatingPanes(2, PaneManagerView.DIRECTION_BACKWARDS);
			}
			
			if(currentPane==1)
			{
				doAnimatingPanes(2, PaneManagerView.DIRECTION_FORWARDS);
			}

			_birthdayReminderSet.setFocus();	

			return true;
		} else if(key==Characters.LATIN_CAPITAL_LETTER_S || key==Characters.LATIN_SMALL_LETTER_S || key==Characters.DIGIT_FOUR)
		{
    		SettingsScreen settingsScreen=new SettingsScreen();
    		UiApplication.getUiApplication().pushModalScreen(settingsScreen);
    		
    		if(settingsScreen.isModified())
    		{
    			int fontSize=settingsScreen.getFontSize();
    			
    			_alarmClockSet.setChildFontSize(fontSize);
    			_worldClockSet.setChildFontSize(fontSize);
    			_birthdayReminderSet.setChildFontSize(fontSize);
    		}
    		
    		settingsScreen=null;
    		
    		return true;
		} else if(key==Characters.LATIN_CAPITAL_LETTER_X || key==Characters.LATIN_SMALL_LETTER_X || key==Characters.DIGIT_EIGHT)
		{
			System.exit(0);
			
			return true;
		} else if(key==Characters.LATIN_CAPITAL_LETTER_P || key==Characters.LATIN_SMALL_LETTER_P)
		{
			int index=_paneManagerView.getModel().currentlySelectedIndex();
			
			switch (index)
			{
				case 0:
					_alarmClockSet.setFocus();
					break;
				case 1:
					_worldClockSet.setFocus();
					break;
				case 2:
					_birthdayReminderSet.setFocus();
					break;
			}
			
			return true;
		//} else if(key==Characters.LATIN_CAPITAL_LETTER_L || key==Characters.LATIN_SMALL_LETTER_L)
		//{
			//Dialog.alert((getLeafFieldWithFocus().getManager()==_worldClockSet)+"");
			
		//	return true;
		//} else if(key==Characters.LATIN_CAPITAL_LETTER_C || key==Characters.LATIN_SMALL_LETTER_C || key==Characters.DIGIT_NINE)
		//{
			//Dialog.alert("Current Pane: " + _paneManagerView.getModel().currentlySelectedIndex());
		} else if(key==Characters.DELETE || key==Characters.BACKSPACE)
		{
			deleteItem();
			
			return true;
		}
		
		return super.keyChar(key, status, time);
	}

	public void clockUpdated()
	{
		ListStyleButtonField link;
		
		if(!_data.isEmpty())
		{
			if(_alarmClockSet.getFieldCount()>0) {}
			
			if(_worldClockSet.getFieldCount()>0)
			{
				String[] dateTime;
				WorldClockSettings worldClockSettings=new WorldClockSettings();
		    	String suffix="";
		    	TimeZone tz;

		    	for(int i=0; i<_dataWorldClockSettings.size(); i++)
		    	{
		    		worldClockSettings=(WorldClockSettings) _dataWorldClockSettings.elementAt(i);
		    		
	    			tz=TimeZone.getTimeZone(worldClockSettings.getTimeZone());
	    			if(tz.useDaylightTime())
	    			{
	    				suffix=" (DST)";
	    			} else {
	    				suffix="";
	    			}
	    			
			    	dateTime=Function.dateTimeNow(tz);
			    	link=(ListStyleButtonField) _worldClockSet.getField(i);
			    	link.setTitleText(worldClockSettings.getCityName());
			    	link.setTimeText(dateTime[1]);
			    	link.setDateText(dateTime[0] + TIMEZONE_DIGITS[worldClockSettings.getCurrentIndex()] + suffix);
		    	}
			}
	    	
			if(_birthdayReminderSet.getFieldCount()>0)
			{
			    Calendar calendarBirthday=Calendar.getInstance(TimeZone.getDefault());
			    Calendar calendarToday=Calendar.getInstance(TimeZone.getDefault());
	    	    Calendar calendarBirthdayTemp=Calendar.getInstance(TimeZone.getDefault());
	    	    Calendar calendarTodayTemp=Calendar.getInstance(TimeZone.getDefault());

			    BirthdayReminderSettings birthdayReminderSettings=new BirthdayReminderSettings();
		    	
		    	for(int i=0; i<_dataBirthdayReminderSettings.size(); i++)
		    	{
		    		birthdayReminderSettings=(BirthdayReminderSettings) _dataBirthdayReminderSettings.elementAt(i);
		    		link=(ListStyleButtonField) _birthdayReminderSet.getField(i);
		    		
		    	    calendarBirthday.setTime(new Date(birthdayReminderSettings.getBirthdayDate()));
		    	    calendarToday.setTime(new Date());
		    	    calendarToday.set(Calendar.HOUR_OF_DAY, 0);
		    	    calendarToday.set(Calendar.MINUTE, 0);
		    	    calendarToday.set(Calendar.SECOND, 0);
		    	    calendarToday.set(Calendar.MILLISECOND, 0);
		    	    
		    	    calendarBirthdayTemp.setTime(calendarBirthday.getTime());
		    	    calendarTodayTemp.setTime(calendarToday.getTime());
		    	    calendarBirthdayTemp.set(Calendar.YEAR, calendarToday.get(Calendar.YEAR));

		    	    String lunarDay="";
		    		if(birthdayReminderSettings.getIsUsingLunar())
		    		{
		    		    int birthYear = calendarBirthday.get(Calendar.YEAR);
		    		    int birthMonth = calendarBirthday.get(Calendar.MONTH)+1;
		    		    int birthDay = calendarBirthday.get(Calendar.DAY_OF_MONTH);
			    	    lunarDay=getLunar(birthYear, birthMonth, birthDay);
		    		    long[] lunar=LunarCalendar.Lunar(birthYear, birthMonth, birthDay);
		    		    long[] lunarTemp=new long[4];
		    		    int count=-1;
		    		    boolean gotIt=false;
		    		    
		    		    while(!gotIt)
		    		    {
		    		    	birthYear = calendarTodayTemp.get(Calendar.YEAR);
		    		    	birthMonth = calendarTodayTemp.get(Calendar.MONTH)+1;
		    		    	birthDay = calendarTodayTemp.get(Calendar.DAY_OF_MONTH);
		    		    	lunarTemp=LunarCalendar.Lunar(birthYear, birthMonth, birthDay);
			    
		    		    	if(lunarTemp[1]==lunar[1] && lunarTemp[2]==lunar[2]) {gotIt=true;}
			    
		    		    	count+=1;
		    		    	calendarTodayTemp.set(Calendar.DAY_OF_MONTH, calendarTodayTemp.get(Calendar.DAY_OF_MONTH)+1);
		    		    }

		    		    birthYear = calendarToday.get(Calendar.YEAR);
		    	    	birthMonth = calendarToday.get(Calendar.MONTH)+1;
		    	    	birthDay = calendarToday.get(Calendar.DAY_OF_MONTH);
		    	    	lunarTemp=LunarCalendar.Lunar(birthYear, birthMonth, birthDay);

		    	    	boolean overDay=false;
		    	    	if(lunarTemp[1]>lunar[1] || (lunarTemp[1]==lunar[1] && lunarTemp[2]>=lunar[2])) {overDay=true;}
		    	    	
		    		    int age=calendarToday.get(Calendar.YEAR)-calendarBirthday.get(Calendar.YEAR)-(overDay ? 0 :1);
		    		    link.setRemainingDaysText(count+getResString(TIPS_REMAINING_DAYS));
		    		    link.setTitleText(birthdayReminderSettings.getBirthdayName() + " (" + age + ")");
		    		} else {
		    			long remainingDays=MathUtilities.round((double) (calendarBirthdayTemp.getTime().getTime()-calendarToday.getTime().getTime())/DateTimeUtilities.ONEDAY);
			    	    int age=calendarToday.get(Calendar.YEAR)-calendarBirthday.get(Calendar.YEAR)-(remainingDays>0 ? 1 : 0);
			    	    if(remainingDays<0) {remainingDays+=DateTimeUtilities.ONEYEAR/DateTimeUtilities.ONEDAY;}
			    	    link.setRemainingDaysText(remainingDays+getResString(TIPS_REMAINING_DAYS));
			    		link.setTitleText(birthdayReminderSettings.getBirthdayName()+" (" + age + ")");
			    	}
		    	
					SimpleDateFormat sdfBirthday=new SimpleDateFormat(SimpleDateFormat.DATE_MEDIUM);
		    		link.setDateOfBirthText(sdfBirthday.formatLocal(calendarBirthday.getTime().getTime())+lunarDay);
		    	}
			}
		}  	 
	}
}